/*
 *
 *
Copyright (c) 1998-2001 Aristar, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. The end-user documentation included with the redistribution, if any,
must include the following acknowledgment:

"This product includes software developed by Aristar, Inc. (http://www.aristar.com/)."

Alternately, this acknowledgment may appear in the software itself, if and
wherever such third-party acknowledgments normally appear.

4. The names "Dialect" and "Aristar, Inc." must not be used to endorse or
promote products derived from this software without prior written permission.
For written permission, please contact info@aristar.com.

5. Products derived from this software may not be called "Dialect", nor may
"Dialect" appear in their name, without prior written permission of Aristar, Inc.

THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
ARISTAR, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This software consists of voluntary contributions made by many individuals
on behalf of Aristar, Inc.  For more information on Aristar, Inc.,
please see <http://www.aristar.com/>.

Portions of this software are based upon software freely available and
written by individuals not associated with Aristar, Inc.  Copyrights are
maintained in the relevant source code files.
 *
 *
 */

#include "stdafx.h"
#include "DConfigGlobals.h"
#include "ADOModule.h"
#include "Interpreter.h"
#include "ADOclasses.h"
#include <afxdisp.h> // COleDateTime

//#include <comdef.h>	// For _variant_t

///////////////////////////////////
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
///////////////////////////////////

#ifdef ADO_SUPPORT
//////////////////////////////////////

#define XERR(x) pInterp->RuntimeError(_T(x))
#define ERR(x) {XERR(x);return AllocNil();}
#define TERR(x) {pInterp->RuntimeError(x);return AllocNil();}

static LPCTSTR lpzWrongNumArgs = _T("Wrong number of arguments to function");
static LPCTSTR lpzExpectString = _T("Expected string argument to function.");
static LPCTSTR lpzExpectInt = _T("Expected integer argument to function");
static LPCTSTR lpzExpectArray = _T("Expected array argument to function");
static LPCTSTR lpzExpectNum = _T("Expected number argument to function");

#define REQUIRE_ARGS(x)		if (argCount != x) TERR(lpzWrongNumArgs)
#define REQUIRE_STRING(x)	if (args[x].Type() != stString) TERR(lpzExpectString)
#define REQUIRE_INTEGER(x)	if ((args[x].Type() != stInteger)) TERR(lpzExpectInt)
#define REQUIRE_ARRAY(x)	if ((args[x].Type() != stArray)) TERR(lpzExpectArray)
#define REQUIRE_NUMBER(x)	if ((args[x].Type() != stInteger) && (args[x].Type() != stFloat)) TERR(lpzExpectNum)

/*#define XERR(x) pInterp->RuntimeError(_T(x))
#define ERR(x) {XERR(x);return AllocNil();}

#define REQUIRE_ARGS(x) if (argCount!=x) ERR("Wrong number of arguments to function.")
#define REQUIRE_STRING(x) if (args[x].Type() != stString) ERR("Expected string in argument(s) to function.")
#define REQUIRE_FLOAT(x) if ((args[x].Type() != stFloat)||(args[x].Type() != stInteger)) ERR("Expected number in argument(s) to function.")
#define REQUIRE_INTEGER(x) if ((args[x].Type() != stInteger)) ERR("Expected integer in arguments(s) to function.")
#define REQUIRE_ARRAY(x) if ((args[x].Type() != stArray)) ERR("Expected array in arguments(s) to function.")
#define REQUIRE_NUMBER(x) \
	if ((args[x].Type() != stInteger) && (args[x].Type() != stFloat)) \
		ERR("Expected number in arguments(s) to function.")
*/

#define BEGIN_METHOD(QType)					\
	ASSERT_SELF(ADO_MODULE_NAME);			\
	VALUE v = self->Get(_T("#ado"));		\
	if (!(v.Boolean())) return AllocNil();	\
	QType* p = (QType*)v.Void()

CORE_FUNC(CantWriteMe)
{
	pInterp->RuntimeError(_T("Can't write to this property"));
	return AllocNil();
}

////////////////////////////////////////////////////////////////

static VALUE __FieldClass;
static VALUE __FieldsClass;
static VALUE CreateFieldInstance(TADOField* pField, CInterpreter* pInterp);
static VALUE CreateFieldsInstance(TADOFields* pFields, CInterpreter* pInterp);

////////////////////////////////////////////////////////////////

static CString BSTRtoCString(const BSTR& s)
{
	//if (sizeof(TCHAR) == 2) {
	//	return (LPCTSTR)s;
	//}
	//else {
		int len = ::SysStringLen(s);

		LPCWSTR lps = s;

		CString result;
		LPTSTR buf = result.GetBuffer(len);
		for (int idx = 0; idx < len; ++idx) {
			buf[idx] = (TCHAR)(lps[idx]);
		}
		result.ReleaseBuffer(len);
		return result;
	//}
}

static CString ADODateToString(double date)
{
	CString result;
	SYSTEMTIME st;
	if (::VariantTimeToSystemTime(date, &st)) {
		//CXTime t(st);
		//return t.ShortDate() + _T(" ") + t.Time();
		//COleDateTime t(st);

		CString d;
		LPTSTR buf = d.GetBuffer(128);
		int count = GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st, NULL, buf, 128);
		d.ReleaseBuffer(count > 0 ? count - 1 : 0);

		CString t;
		buf = t.GetBuffer(128);
		count = GetTimeFormat(LOCALE_USER_DEFAULT, 0, &st, NULL, buf, 128);
		t.ReleaseBuffer(count > 0 ? count - 1 : 0);

		result = d + _T(" ") + t;
	}
	return result;
}

bool VariantToValue(const VARIANT& var, VALUE& value)
{
	if (var.vt & VT_BYREF) {
		switch (var.vt ^ VT_BYREF) {
			case VT_UI1:	value = (int)*var.pbVal;	break;	// Unsigned char
			case VT_I2:		value = (int)*var.piVal;	break;	// Short
			case VT_I4:		value = (int)*var.plVal;	break;	// Long
			case VT_R4:		value = *var.pfltVal;		break;	// Float
			case VT_R8:		value = (float)*var.pdblVal;break;	// Double
			case VT_BOOL:	value = (bool)(*var.pboolVal == VARIANT_TRUE);	break;	// Boolean
			case VT_BSTR:	value = BSTRtoCString(*var.pbstrVal);	break;
			case VT_DATE:	value = ADODateToString(*var.pdate);
							if (value.String().IsEmpty()) return false;
							break;
			//SCODE                    FAR* pscode;            // VT_BYREF|VT_ERROR.
			//CY                        FAR* pcyVal;            // VT_BYREF|VT_CY.
			//SAFEARRAY FAR*        FAR* pparray;            // VT_ARRAY|*.
			//VARIANT                FAR* pvarVal;            // VT_BYREF|VT_VARIANT.
			default: return false;
		}
	}
	else {
		switch (var.vt) {
			case VT_NULL:	value = AllocNil();			break;
			case VT_EMPTY:	value = AllocNil();			break;
			case VT_UI1:	value = (int)var.bVal;		break;	// Unsigned char
			case VT_I2:		value = (int)var.iVal;		break;	// Short
			case VT_I4:		value = (int)var.lVal;		break;	// Long
			case VT_R4:		value = var.fltVal;			break;	// Float
			case VT_R8:		value = (float)var.dblVal;	break;	// Double
			case VT_BOOL:	value = (bool)(var.boolVal == VARIANT_TRUE);	break;	// Boolean
			case VT_BSTR:	value = BSTRtoCString(var.bstrVal);	break;
			case VT_DATE:	value = ADODateToString(var.date);
							if (value.String().IsEmpty()) return false;
							break;
			//SCODE                    scode;                    // VT_ERROR.
			//CY                        cyVal;                    // VT_CY    .
			//SAFEARRAY            FAR* parray;            // VT_ARRAY|*.
			default: return false;
		}
	}
	return true;
}

bool ValueToVariant(const VALUE& value, VARIANT& var)
{
	VariantClear(&var);
	VariantInit(&var);

#ifndef UNDER_CE
	OLECHAR* buf;
	int length, idx;
	LPCSTR str;
#endif

	switch (value.Type()) {
		case stString:
			var.vt = VT_BSTR;
#ifdef UNDER_CE
			var.bstrVal = ::SysAllocString((LPCTSTR)value.String());
#else
			str = value.String();
			length = value.String().GetLength();
			buf = new OLECHAR[length + 1];
			for (idx = 0; idx <= length; ++idx) {
				buf[idx] = (OLECHAR)(str[idx]);
			}
			var.bstrVal = SysAllocString(buf);
			delete[] buf;
#endif
			break;
		case stInteger:
			var.vt = VT_I4;
			var.lVal = (long)value.Integer();
			break;
		case stFloat:
			var.vt = VT_R4;
			var.fltVal = value.Float();
			break;
		case stBoolean:
			var.vt = VT_BOOL;
			var.boolVal = value.Boolean() ? VARIANT_TRUE : VARIANT_FALSE;
			break;
		case stNil:
			var.vt = VT_NULL; // Should we do NULL or EMPTY for nil?
			var.lVal = 0;
			break;
		default:
			return false;
	}
	return true;
}

////////////////////////////////////////////////////////////////
// The ado.connection class

#ifndef UNDER_CE

static void FreeConnection(void *pVoid)
{
	delete (TADOConnection*)pVoid;
}

CORE_FUNC(Connection__init__)
{
	// ado.connection()
	ASSERT_SELF(ADO_MODULE_NAME);
	if (argCount != 0) {
		ERR("ado.connection() requires zero arguments");
	}
	TADOConnection* pCon = new TADOConnection();
	self->Set(_T("#ado"), AllocVoid(pCon, FreeConnection, _T("connection")));
	return VALUE();
}

CORE_FUNC(Connection_open)
{
	if (argCount != 4) {
		ERR("connection.open() requires 4 args");
	}
	BEGIN_METHOD(TADOConnection);
	if (!p->Open(args[0].String(), args[1].String(), args[2].String(), args[3].Integer())) {
		pInterp->RuntimeError(_T("connection.open() failed: ") + p->GetLastError());
	}
	return AllocNil();
}

CORE_FUNC(Connection_close)
{
	if (argCount != 0) {
		ERR("connection.close() requires zero args");
	}
	BEGIN_METHOD(TADOConnection);
	if (!p->Close()) {
		pInterp->RuntimeError(_T("connection.close() failed: ") + p->GetLastError());
	}
	return AllocNil();
}

CORE_FUNC(Connection_ReadProvider)
{
	ASSERT(argCount == 1);
	BEGIN_METHOD(TADOConnection);
	CString provider;
	if (!p->GetProvider(&provider)) {
		pInterp->RuntimeError(_T("connection.provider failed: ") + p->GetLastError());
	}
	return provider;
}

CORE_FUNC(Connection_WriteProvider)
{
	ASSERT(argCount == 2);
	BEGIN_METHOD(TADOConnection);
	if (!p->SetProvider(args[1].String())) {
		pInterp->RuntimeError(_T("connection.provider failed: ") + p->GetLastError());
	}
	return args[1];
}

CORE_FUNC(Connection_ReadState)
{
	ASSERT(argCount == 1);
	BEGIN_METHOD(TADOConnection);
	long state;
	if (!p->GetState(&state)) {
		pInterp->RuntimeError(_T("connection.state failed: ") + p->GetLastError());
	}
	return (int)state;
}

static VALUE ConnectionClass()
{
	VALUE v = AllocClass(_T("connection"), VALUE());
	v.Set(_T("__init__"), AllocFunction(Connection__init__, ADO_MODULE_NAME));
	v.Set(_T("open"), AllocFunction(Connection_open, ADO_MODULE_NAME));
	v.Set(_T("close"), AllocFunction(Connection_close, ADO_MODULE_NAME));
	v.Set(_T("provider"), AllocProperty(
		AllocFunction(Connection_ReadProvider, ADO_MODULE_NAME),
		AllocFunction(Connection_WriteProvider, ADO_MODULE_NAME),
		AllocNil()));
	v.Set(_T("state"), AllocProperty(
		AllocFunction(Connection_ReadState, ADO_MODULE_NAME),
		AllocFunction(CantWriteMe, ADO_MODULE_NAME),
		AllocNil()));
	return v;
}

#endif // UNDER_CE

////////////////////////////////////////////////////////////////
// The ado.Recordset class

static void FreeRecordset(void *pVoid)
{
	delete (TADORecordset*)pVoid;
}

CORE_FUNC(Recordset__init__)
{
	// ado.connection()
	ASSERT_SELF(ADO_MODULE_NAME);
	if (argCount != 0) {
		ERR("ado.recordset() requires zero arguments");
	}
	TADORecordset* pRs = new TADORecordset();
	self->Set(_T("#ado"), AllocVoid(pRs, FreeRecordset, _T("recordset")));
	return VALUE();
}

CORE_FUNC(Recordset_open)
{
	if (argCount != 5) {
		ERR("recordset.open() requires 5 args");
	}
	BEGIN_METHOD(TADORecordset);
	if (args[1].Type() == stClassInstance) {
#ifdef UNDER_CE
		pInterp->RuntimeError(_T("recordset.open() invalid second arg") + p->GetLastError());
		return AllocNil();
#else
		TADOConnection* pCon = (TADOConnection*)args[1][_T("#ado")].Void();
		if (!pCon || !p->Open(args[0].String(), *pCon, args[2].Integer(),
			args[3].Integer(), args[4].Integer()))
		{
			pInterp->RuntimeError(_T("recordset.open() failed: ") + p->GetLastError());
			return AllocNil();
		}
#endif
	}
	else {
		if (!p->Open(args[0].String(), args[1].String(), args[2].Integer(),
			args[3].Integer(), args[4].Integer()))
		{
			pInterp->RuntimeError(_T("recordset.open() failed: ") + p->GetLastError());
			return AllocNil();
		}
	}

	// Now create the fields instance that goes with this record
	TADOFields* pFields = new TADOFields();
	if (!p->GetFields(pFields)) {
		delete pFields;
		pInterp->RuntimeError(_T("recordset.open (creating fields member): ") + p->GetLastError());
	}
	else self->Set(_T("fields"), CreateFieldsInstance(pFields, pInterp));

	return AllocNil();
}

CORE_FUNC(Recordset_close)
{
	if (argCount != 0) {
		ERR("recordset.close() requires zero args");
	}
	BEGIN_METHOD(TADORecordset);
	if (!p->Close()) {
		pInterp->RuntimeError(_T("recordset.close() failed: ") + p->GetLastError());
	}
	self->Set(_T("fields"), AllocNil());	// No longer valid, eh?
	return AllocNil();
}

CORE_FUNC(Recordset_getstring)
{
	if (argCount != 5) {
		ERR("recordset.getstring() requires 5 args");
	}
	BEGIN_METHOD(TADORecordset);
	CString result;
	if (!p->GetString(args[0].Integer(), args[1].Integer(), args[2].String(),
		args[3].String(), args[4].String(), &result))
	{
		pInterp->RuntimeError(_T("recordset.getstring() failed: ") + p->GetLastError());
	}
	return result;
}

CORE_FUNC(Recordset_ReadRecordCount)
{
	ASSERT(argCount == 1);
	BEGIN_METHOD(TADORecordset);
	long count;
	if (!p->GetRecordCount(&count)) {
		pInterp->RuntimeError(_T("recordset.recordcount: ") + p->GetLastError());
	}
	return (int)count;
}

CORE_FUNC(Recordset_ReadBOF)
{
	ASSERT(argCount == 1);
	BEGIN_METHOD(TADORecordset);
	bool bBOF;
	if (!p->GetBOF(&bBOF)) {
		pInterp->RuntimeError(_T("recordset.BOF: ") + p->GetLastError());
	}
	return bBOF;
}

CORE_FUNC(Recordset_ReadEOF)
{
	ASSERT(argCount == 1);
	BEGIN_METHOD(TADORecordset);
	bool bEOF;
	if (!p->GetEOF(&bEOF)) {
		pInterp->RuntimeError(_T("recordset.EOF: ") + p->GetLastError());
	}
	return bEOF;
}

CORE_FUNC(Recordset_Update)
{
	BEGIN_METHOD(TADORecordset);
	if (!p->Update()) {
		pInterp->RuntimeError(_T("recordset.update(): ") + p->GetLastError());
	}
	return AllocNil();
}

CORE_FUNC(Recordset_CancelUpdate)
{
	BEGIN_METHOD(TADORecordset);
	if (!p->CancelUpdate()) {
		pInterp->RuntimeError(_T("recordset.cancelupdate(): ") + p->GetLastError());
	}
	return AllocNil();
}

CORE_FUNC(Recordset_MoveFirst)
{
	BEGIN_METHOD(TADORecordset);
	if (!p->MoveFirst()) {
		pInterp->RuntimeError(_T("recordset.movefirst(): ") + p->GetLastError());
	}
	return AllocNil();
}

CORE_FUNC(Recordset_MoveNext)
{
	BEGIN_METHOD(TADORecordset);
	if (!p->MoveNext()) {
		pInterp->RuntimeError(_T("recordset.movenext(): ") + p->GetLastError());
	}
	return AllocNil();
}

CORE_FUNC(Recordset_MoveLast)
{
	BEGIN_METHOD(TADORecordset);
	if (!p->MoveLast()) {
		pInterp->RuntimeError(_T("recordset.movelast(): ") + p->GetLastError());
	}
	return AllocNil();
}

CORE_FUNC(Recordset_MovePrevious)
{
	BEGIN_METHOD(TADORecordset);
	if (!p->MovePrevious()) {
		pInterp->RuntimeError(_T("recordset.moveprevious(): ") + p->GetLastError());
	}
	return AllocNil();
}

CORE_FUNC(Recordset_Delete)
{
	if (argCount > 1) {
		pInterp->RuntimeError(_T("recordset.delete() takes zero or one argument"));
		return AllocNil();
	}

#ifdef UNDER_CE
	long ae = 1;
	if (argCount == 1) ae = args[0].Integer();
#else
	AffectEnum ae = adAffectCurrent;
	if (argCount == 1) ae = static_cast<AffectEnum>(args[0].Integer());
#endif

	BEGIN_METHOD(TADORecordset);
	if (!p->Delete()) {
		pInterp->RuntimeError(_T("recordset.delete(): ") + p->GetLastError());
	}
	return AllocNil();
}

CORE_FUNC(Recordset_AddNew)
{
	if (argCount > 0) {
		pInterp->RuntimeError(_T("recordset.addnew() takes zero arguments"));
		return AllocNil();
	}
	BEGIN_METHOD(TADORecordset);
	if (!p->AddNew()) {
		pInterp->RuntimeError(_T("recordset.addnew(): ") + p->GetLastError());
	}
	return AllocNil();
}

CORE_FUNC(Recordset_ReadAbsolutePos)
{
	ASSERT(argCount == 1);
	BEGIN_METHOD(TADORecordset);
	long pos;
	if (!p->GetAbsolutePosition(&pos)) {
		pInterp->RuntimeError(_T("recordset.absoluteposition: ") + p->GetLastError());
	}
	return (int)pos;
}

CORE_FUNC(Recordset_WriteAbsolutePos)
{
	REQUIRE_ARGS(2);
	REQUIRE_INTEGER(1);
	BEGIN_METHOD(TADORecordset);
	if (!p->SetAbsolutePosition(args[1].Integer())) {
		pInterp->RuntimeError(_T("recordset.absoluteposition: ") + p->GetLastError());
	}
	return AllocNil();
}

#ifndef UNDER_CE
CORE_FUNC(Recordset_Find)
{
	if ((argCount < 1) || (argCount > 4)) {
		pInterp->RuntimeError(_T("recordset.find() takes one to four arguments"));
		return AllocNil();
	}

	CString criteria = args[0].String();
	long skipRecs = 0;
	SearchDirectionEnum srchDir = adSearchForward;
	_variant_t start = (long)adBookmarkCurrent;

	if (argCount >= 2) {
		skipRecs = args[1].Integer();
		if (argCount >= 3) {
			srchDir = static_cast<SearchDirectionEnum>(args[2].Integer());
			if (argCount >= 4) {
				start = (long)args[3].Integer(); // Not sure this is correct
			}
		}
	}

	BEGIN_METHOD(TADORecordset);
	if (!p->Find(criteria, skipRecs, srchDir, start)) {
		pInterp->RuntimeError(_T("recordset.find(): ") + p->GetLastError());
	}
	return AllocNil();
}
#endif

static VALUE RecordsetClass()
{
	VALUE v = AllocClass(_T("recordset"), VALUE());
	v.Set(_T("__init__"), AllocFunction(Recordset__init__, ADO_MODULE_NAME));
	v.Set(_T("open"), AllocFunction(Recordset_open, ADO_MODULE_NAME));
	v.Set(_T("close"), AllocFunction(Recordset_close, ADO_MODULE_NAME));
	v.Set(_T("delete"), AllocFunction(Recordset_Delete, ADO_MODULE_NAME));
	v.Set(_T("addnew"), AllocFunction(Recordset_AddNew, ADO_MODULE_NAME));
	v.Set(_T("update"), AllocFunction(Recordset_Update, ADO_MODULE_NAME));
	v.Set(_T("cancelupdate"), AllocFunction(Recordset_CancelUpdate, ADO_MODULE_NAME));
#ifndef UNDER_CE
	v.Set(_T("find"), AllocFunction(Recordset_Find, ADO_MODULE_NAME));
#endif
	v.Set(_T("movefirst"), AllocFunction(Recordset_MoveFirst, ADO_MODULE_NAME));
	v.Set(_T("movelast"), AllocFunction(Recordset_MoveLast, ADO_MODULE_NAME));
	v.Set(_T("movenext"), AllocFunction(Recordset_MoveNext, ADO_MODULE_NAME));
	v.Set(_T("moveprevious"), AllocFunction(Recordset_MovePrevious, ADO_MODULE_NAME));
	//v.Set(_T("getstring"), AllocFunction(Recordset_getstring, ADO_MODULE_NAME));
	v.Set(_T("absoluteposition"), AllocProperty(
		AllocFunction(Recordset_ReadAbsolutePos, ADO_MODULE_NAME),
		AllocFunction(Recordset_WriteAbsolutePos, ADO_MODULE_NAME),
		AllocNil()));
	v.Set(_T("recordcount"), AllocProperty(
		AllocFunction(Recordset_ReadRecordCount, ADO_MODULE_NAME),
		AllocFunction(CantWriteMe, ADO_MODULE_NAME),
		AllocNil()));
	v.Set(_T("bof"), AllocProperty(
		AllocFunction(Recordset_ReadBOF, ADO_MODULE_NAME),
		AllocFunction(CantWriteMe, ADO_MODULE_NAME),
		AllocNil()));
	v.Set(_T("eof"), AllocProperty(
		AllocFunction(Recordset_ReadEOF, ADO_MODULE_NAME),
		AllocFunction(CantWriteMe, ADO_MODULE_NAME),
		AllocNil()));
	return v;
}

////////////////////////////////////////////////////////////////
// The ado.fields class
// The fields class will never be instantiated by a user, only
// by an instance of the recordset class, so we don't need a real
// __init__ constructor.

static void FreeFields(void *pVoid)
{
	delete (TADOFields*)pVoid;
}

static VALUE CreateFieldsInstance(TADOFields* pFields, CInterpreter* pInterp)
{
	VALUE v = AllocClassInstance(__FieldsClass, pInterp);
	v.Set(_T("#ado"), AllocVoid(pFields, FreeFields, _T("fields")));
	return v;
}

CORE_FUNC(Fields_readcount)
{
	ASSERT(argCount == 1);
	BEGIN_METHOD(TADOFields);
	long count;
	if (!p->GetCount(&count)) {
		pInterp->RuntimeError(_T("fields.count: ") + p->GetLastError());
	}
	return (int)count;
}

CORE_FUNC(Fields_item)
{
	BEGIN_METHOD(TADOFields);
	if (argCount != 1) {
		ERR("fields.item() requires one integer or string argument");
	}
	else if (args[0].Type() == stInteger) {
		TADOField* pField = new TADOField();
		if (!p->GetItem(args[0].Integer(), pField)) {
			delete pField;
			pInterp->RuntimeError(_T("fields.item(): ") + p->GetLastError());
			return AllocNil();
		}
		VALUE vField = CreateFieldInstance(pField, pInterp);
		self->Set(_T("#lastfield"), vField); // Must hold to avoid early GC
		return vField;
	}
	else if (args[0].Type() == stString) {
		TADOField* pField = new TADOField();
		if (!p->GetItem(args[0].String(), pField)) {
			delete pField;
			pInterp->RuntimeError(_T("fields.item(): ") + p->GetLastError());
			return AllocNil();
		}
		VALUE vField = CreateFieldInstance(pField, pInterp);
		self->Set(_T("#lastfield"), vField); // Must hold to avoid early GC
		return vField;
	}
	else {
		ERR("fields.item() requires one integer or string argument");
	}
}

static VALUE FieldsClass()
{
	VALUE v = AllocClass(_T("fields"), VALUE());
	v.Set(_T("count"), AllocProperty(
		AllocFunction(Fields_readcount, ADO_MODULE_NAME),
		AllocFunction(CantWriteMe, ADO_MODULE_NAME),
		AllocNil()));
	v.Set(_T("item"), AllocFunction(Fields_item, ADO_MODULE_NAME));
	return v;
}

////////////////////////////////////////////////////////////////
// The ado.field class
// The field class will never be instantiated by a user, only
// by an instance of the recordset class, so we don't need a real
// __init__ constructor.

static void FreeField(void *pVoid)
{
	delete (TADOField*)pVoid;
}

static VALUE CreateFieldInstance(TADOField* pField, CInterpreter* pInterp)
{
	VALUE v = AllocClassInstance(__FieldClass, pInterp);
	v.Set(_T("#ado"), AllocVoid(pField, FreeField, _T("field")));
	return v;
}

CORE_FUNC(Field_readname)
{
	ASSERT(argCount == 1);
	BEGIN_METHOD(TADOField);
	CString name;
	if (!p->GetName(&name)) {
		pInterp->RuntimeError(_T("field.name: ") + p->GetLastError());
	}
	return name;
}

CORE_FUNC(Field_readtype)
{
	ASSERT(argCount == 1);
	BEGIN_METHOD(TADOField);
	DataTypeEnum type;
	if (!p->GetType(&type)) {
		pInterp->RuntimeError(_T("field.type: ") + p->GetLastError());
	}
	return static_cast<long>(type);
}

CORE_FUNC(Field_readdefinedsize)
{
	ASSERT(argCount == 1);
	BEGIN_METHOD(TADOField);
	long size;
	if (!p->GetDefinedSize(&size)) {
		pInterp->RuntimeError(_T("field.definedSize: ") + p->GetLastError());
	}
	return size;
}

CORE_FUNC(Field_readactualsize)
{
	ASSERT(argCount == 1);
	BEGIN_METHOD(TADOField);
	long size;
	if (!p->GetActualSize(&size)) {
		pInterp->RuntimeError(_T("field.actualSize: ") + p->GetLastError());
	}
	return size;
}

CORE_FUNC(Field_readvalue)
{
	ASSERT(argCount == 1);
	BEGIN_METHOD(TADOField);
	VALUE value;
#ifdef UNDER_CE
	VARIANT var;
#else
	_variant_t var;
#endif
	if (!p->GetValue(&var)) {
		pInterp->RuntimeError(_T("field.value: ") + p->GetLastError());
	}
	else if (!VariantToValue(var, value)) {
		pInterp->RuntimeError(_T("field.value: Unable to convert VARIANT to a Dialect value"));
	}
	VariantClear(&var); // For CE version
	return value;
}

CORE_FUNC(Field_writevalue)
{
	ASSERT(argCount == 2);
	BEGIN_METHOD(TADOField);
#ifdef UNDER_CE
	VARIANT var;
#else
	_variant_t var;
#endif
	if (!ValueToVariant(args[1], var) || !p->SetValue(var)) {
		pInterp->RuntimeError(_T("field.value: ") + p->GetLastError());
	}
	VariantClear(&var); // For CE version
	return args[1];
}

static VALUE FieldClass()
{
	VALUE v = AllocClass(_T("field"), VALUE());
	v.Set(_T("name"), AllocProperty(
		AllocFunction(Field_readname, ADO_MODULE_NAME),
		AllocFunction(CantWriteMe, ADO_MODULE_NAME),
		AllocNil()));
	v.Set(_T("definedSize"), AllocProperty(
		AllocFunction(Field_readdefinedsize, ADO_MODULE_NAME),
		AllocFunction(CantWriteMe, ADO_MODULE_NAME),
		AllocNil()));
	v.Set(_T("actualSize"), AllocProperty(
		AllocFunction(Field_readactualsize, ADO_MODULE_NAME),
		AllocFunction(CantWriteMe, ADO_MODULE_NAME),
		AllocNil()));
	v.Set(_T("value"), AllocProperty(
		AllocFunction(Field_readvalue, ADO_MODULE_NAME),
		AllocFunction(Field_writevalue, ADO_MODULE_NAME),
		AllocNil()));
	v.Set(_T("type"), AllocProperty(
		AllocFunction(Field_readtype, ADO_MODULE_NAME),
		AllocFunction(CantWriteMe, ADO_MODULE_NAME),
		AllocNil()));
	return v;
}

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

VALUE InitADOModule()
{
	VALUE module = AllocFrame();
	module.Set(_T("__module__"), ADO_MODULE_NAME);

#ifndef UNDER_CE
	//---- ObjectStateEnum Values ----
	module.Set(_T("adStateClosed"), (int)adStateClosed);
	module.Set(_T("adStateOpen"), (int)adStateOpen);
	module.Set(_T("adStateConnecting"), (int)adStateConnecting);
	module.Set(_T("adStateExecuting"), (int)adStateExecuting);
	module.Set(_T("adStateFetching"), (int)adStateFetching);
#endif

	//---- EditModeEnum Values ----
	module.Set(_T("adEditNone"), (int)adEditNone);
	module.Set(_T("adEditInProgress"), (int)adEditInProgress);
	module.Set(_T("adEditAdd"), (int)adEditAdd);
#ifndef UNDER_CE
	module.Set(_T("adEditDelete"), (int)adEditDelete);
#endif

	//---- CursorTypeEnum Values ----
	module.Set(_T("adOpenForwardOnly"), (int)adOpenForwardOnly);
	module.Set(_T("adOpenKeyset"), (int)adOpenKeyset);
	module.Set(_T("adOpenDynamic"), (int)adOpenDynamic);
	module.Set(_T("adOpenStatic"), (int)adOpenStatic);

	//---- LockTypeEnum Values ----
	module.Set(_T("adLockReadOnly"), (int)adLockReadOnly);
	module.Set(_T("adLockOptimistic"), (int)adLockOptimistic);
#ifndef UNDER_CE
	module.Set(_T("adLockPessimistic"), (int)adLockPessimistic);
	module.Set(_T("adLockBatchOptimistic"), (int)adLockBatchOptimistic);
#endif

	//---- CommandTypeEnum Values ----
	module.Set(_T("adCmdUnknown"), (int)adCmdUnknown);
	module.Set(_T("adCmdText"), (int)adCmdText);
	module.Set(_T("adCmdTable"), (int)adCmdTable);
	module.Set(_T("adCmdStoredProc"), (int)adCmdStoredProc);
#ifndef UNDER_CE
	module.Set(_T("adCmdFile"), (int)adCmdFile);
	module.Set(_T("adCmdTableDirect"), (int)adCmdTableDirect);
#endif

	//---- AffectEnum Values ----
#ifndef UNDER_CE
	module.Set(_T("adAffectCurrent"), (int)adAffectCurrent);
	module.Set(_T("adAffectGroup"), (int)adAffectGroup);
	module.Set(_T("adAffectAll"), (int)adAffectAll);
	module.Set(_T("adAffectAllChapters"), (int)adAffectAllChapters);
#endif

	//---- PositionEnum Values ----
	module.Set(_T("adPosUnknown"), (int)adPosUnknown);
	module.Set(_T("adPosBOF"), (int)adPosBOF);
	module.Set(_T("adPosEOF"), (int)adPosEOF);

	//---- SearchDirectionEnum Values ----
#ifndef UNDER_CE
	module.Set(_T("adSearchForward"), (int)adSearchForward);
	module.Set(_T("adSearchBackward"), (int)adSearchBackward);
#endif

	//---- StringFormatEnum Values ----
#ifndef UNDER_CE
	//module.Set(_T("adStringXML"), (int)adStringXML);
	//module.Set(_T("adStringHTML"), (int)adStringHTML);
	module.Set(_T("adClipString"), (int)adClipString);
#endif

#ifndef UNDER_CE
	//---- Bookmarks ----
	module.Set(_T("adBookmarkCurrent"), (int)adBookmarkCurrent);
	module.Set(_T("adBookmarkFirst"), (int)adBookmarkFirst);
	module.Set(_T("adBookmarkLast"), (int)adBookmarkLast);
#endif

#ifndef UNDER_CE
	//---- RecordStatusEnum Values ----
	module.Set(_T("adRecOK"), (int)adRecOK);
	module.Set(_T("adRecNew"), (int)adRecNew);
	module.Set(_T("adRecModified"), (int)adRecModified);
	module.Set(_T("adRecDeleted"), (int)adRecDeleted);
	module.Set(_T("adRecUnmodified"), (int)adRecUnmodified);
	module.Set(_T("adRecInvalid"), (int)adRecInvalid);
	module.Set(_T("adRecMultipleChanges"), (int)adRecMultipleChanges);
	module.Set(_T("adRecPendingChanges"), (int)adRecPendingChanges);
	module.Set(_T("adRecCanceled"), (int)adRecCanceled);
	module.Set(_T("adRecCantRelease"), (int)adRecCantRelease);
	module.Set(_T("adRecConcurrencyViolation"), (int)adRecConcurrencyViolation);
	module.Set(_T("adRecIntegrityViolation"), (int)adRecIntegrityViolation);
	module.Set(_T("adRecMaxChangesExceeded"), (int)adRecMaxChangesExceeded);
	module.Set(_T("adRecObjectOpen"), (int)adRecObjectOpen);
	module.Set(_T("adRecOutOfMemory"), (int)adRecOutOfMemory);
	module.Set(_T("adRecPermissionDenied"), (int)adRecPermissionDenied);
	module.Set(_T("adRecSchemaViolation"), (int)adRecSchemaViolation);
	module.Set(_T("adRecDBDeleted"), (int)adRecDBDeleted);
#endif

	//---- DataTypeEnum ----
#ifndef UNDER_CE
    module.Set(_T("adEmpty"), (int)adEmpty);
	module.Set(_T("adTinyInt"), (int)adTinyInt);
	module.Set(_T("adBigInt"), (int)adBigInt);
	module.Set(_T("adUnsignedTinyInt"), (int)adUnsignedTinyInt);
	module.Set(_T("adUnsignedBigInt"), (int)adUnsignedBigInt);
	module.Set(_T("adSingle"), (int)adSingle);
	module.Set(_T("adCurrency"), (int)adCurrency);
	module.Set(_T("adDecimal"), (int)adDecimal);
	module.Set(_T("adNumeric"), (int)adNumeric);
	module.Set(_T("adError"), (int)adError);
	module.Set(_T("adUserDefined"), (int)adUserDefined);
	module.Set(_T("adVariant"), (int)adVariant);
	module.Set(_T("adIDispatch"), (int)adIDispatch);
	module.Set(_T("adIUnknown"), (int)adIUnknown);
	module.Set(_T("adGUID"), (int)adGUID);
	module.Set(_T("adDBDate"), (int)adDBDate);
	module.Set(_T("adDBTime"), (int)adDBTime);
	module.Set(_T("adDBTimeStamp"), (int)adDBTimeStamp);
	module.Set(_T("adBSTR"), (int)adBSTR);
	module.Set(_T("adChar"), (int)adChar);
	module.Set(_T("adVarChar"), (int)adVarChar);
	module.Set(_T("adLongVarChar"), (int)adLongVarChar);
	module.Set(_T("adWChar"), (int)adWChar);
	module.Set(_T("adVarBinary"), (int)adVarBinary);
	module.Set(_T("adLongVarBinary"), (int)adLongVarBinary);
	module.Set(_T("adChapter"), (int)adChapter);
	module.Set(_T("adFileTime"), (int)adFileTime);
	//module.Set(_T("adDBFileTime"), (int)adDBFileTime);
	module.Set(_T("adPropVariant"), (int)adPropVariant);
	module.Set(_T("adVarNumeric"), (int)adVarNumeric);
#endif
	module.Set(_T("adSmallInt"), (int)adSmallInt);
	module.Set(_T("adInteger"), (int)adInteger);
	module.Set(_T("adUnsignedSmallInt"), (int)adUnsignedSmallInt);
	module.Set(_T("adUnsignedInt"), (int)adUnsignedInt);
	module.Set(_T("adDouble"), (int)adDouble);
	module.Set(_T("adBoolean"), (int)adBoolean);
	module.Set(_T("adDate"), (int)adDate);
	module.Set(_T("adVarWChar"), (int)adVarWChar);
	module.Set(_T("adLongVarWChar"), (int)adLongVarWChar);
	module.Set(_T("adBinary"), (int)adBinary);

	// No need to register the fields and field classes
	// though, make the masters for use by recordset
	__FieldClass = FieldClass();
	__FieldsClass = FieldsClass();

#ifndef UNDER_CE
	module.Set(_T("connection"), ConnectionClass());
#endif
	module.Set(_T("recordset"), RecordsetClass());

	return module;
}

//////////////////////////////////////
#endif // ADO_SUPPORT